<template>
  <header>
    <div class="user">
      <b>用户名</b>
      <button @click="to">退出登录</button>
    </div>
    <nav>
      <router-link 
    v-for="(item,index) in navlist" 
    :key="item.name"
    :to="item.path"
    >{{ item.name }}
        <span @click.prevent = del(index)>x</span>
      </router-link>
    </nav>
  </header>
</template>

<script>
import { navConfig } from '../data';
export default {
  data() {
    return {
      navlist:[]
    }
  },
  watch: {
    $route: {
      handler() {
        const cur = navConfig.find(v => v.path === this.$route.path)
        if(cur && this.navlist.indexOf(cur) === -1) {
          this.navlist.push(cur) 
        }
      },
      immediate:true
    }
  },
  methods:{
    del(index) {
      if(this.navlist.length === 1) {
        this.navlist = []
        this.$router.push('/login')
        this.$message.success('退出登录')
        return
      }
      // 判断要删除的是不是当前选中的页面
      if(this.$route.path === this.navlist[index].path) {
        // 判断当前是不是最后一个
        if(index === this.navlist.length - 1) {
          this.$router.push(this.navlist[index-1].path)
        }else {
          this.$router.push(this.navlist[index+1].path)
        }
      }
      this.navlist.splice(index,1)
      localStorage.removeItem('token')
    },
    to() {
      this.$router.replace('/login')
      localStorage.removeItem('token')
    }
  }
}
</script>

<style lang="scss" scoped>
header{
    height: 120px;
    border-bottom: 1px solid #ccc;
}
.user {
  height: 70px;
  border-bottom: 1px solid #eeeeee;
  text-align: right;
  line-height: 40px;
  button{
    margin: 0 10px;
    cursor: pointer;
  }
}
nav {
  height: 50px;
  line-height: 50px;
  display: flex;
  a {
    margin: 0 10px;
    background: #ddd;
    padding: 0 10px;
    display: block;
  }
  span {
    padding: 0 5px;
  }
  span:hover {
    background: #ccc;
    cursor: pointer;
  }
  .router-link-active{
    background: tomato;
  }
}
</style>